import csv
import os
import datetime
from settings import INFO_CSV_DIR
from tools import hd_logger
logger = hd_logger.HdLogger()


def get_time_now_string_year_month_day():
    """
    日志管理,如果日志目录不存在就创建,如果日志目录存在了,就将日志吸入到当前的目录中.日志的目录也保存到D盘固定位置,不要跟随项目走了.
    :return:
    """
    nowTime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
    
    try:
        for root, _, filenames in os.walk(INFO_CSV_DIR):
            for filename in filenames:
                day = filename[8:10]
                month = filename[5:7]
                now_day = nowTime[8:10]
                now_month = nowTime[5:7]
                if now_day == day and now_month != month:  # 如果天数对应得上,但是月数不同,就删除上个月同一天的日志信息
                    os.remove(os.path.join(INFO_CSV_DIR, filename))
    except Exception as e:
        errorInfo = "in log_check() error : {}".format(str(e))
        print(errorInfo)
    return nowTime


def write_info_to_csv(data, joinNumber="4"):
    try:
        csvFailPath = os.path.join(INFO_CSV_DIR, "{}_{}.csv".format(get_time_now_string_year_month_day(),joinNumber))
        if not os.path.exists(csvFailPath):
            with open(csvFailPath, 'w', encoding='utf-8-sig', newline='') as f:
                columns =('id',
                          "起点检测",
                          "起点检测角度","起点检测板边到铡刀距离","第一块板长","移动距离","移动补偿",
                          "终点检测",
                          "1号相机","1号灯管","2号灯管","第二块板长","角度","误差",
                          "2号相机","3号灯管","4号灯管","第一块板长","角度","误差",
                          "总偏差","验证通过","前角","后角","第一块偏","第二块偏","是否易断板")
                writer = csv.writer(f)
                writer.writerow(columns)
        with open(csvFailPath, 'a', encoding='utf-8-sig', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(data)
    except Exception as e:
        errorInfo = "in write_info_to_csv() error: {}".format(e)
        print(errorInfo)
        logger.debug(errorInfo)

if __name__ == '__main__':
    data = ('4414', '-1.99', '-1.14', '-0.85', '5.68', '易断板')
    write_info_to_csv(data,'2')


